﻿using System;
using System.Linq;
using Pay.Core;
using Pay.Data;
using Pay.DTO;
using Pay.IService;
using Pay.Service.Cache;
using Pay.TO;

namespace Pay.Service.Service {
    public class GoodDeclarationService : ServiceBase, IGoodDeclarationService, IDisposable {
        private IUnitOfWork _iUnitOfWork;

        public GoodDeclarationService(IUnitOfWork iUnitOfWork)
             : base(iUnitOfWork) {
            _iUnitOfWork = iUnitOfWork;
        }

        public PagedResult<good_declaration_dto> GetGoodDeclarations(GoodDeclarationQuery query) {
            var filter = PredicateBuilder.True<GoodDeclaration>();
            var auth_status = Convert.ToInt32(query.auth_status);
            if (query.merchant_id > 0)
                filter = filter.And(c => c.MerchantId == query.merchant_id);
            if (!String.IsNullOrEmpty(query.auth_status))
                filter = filter.And(c => c.AuditStatus == (GoodDeclarationStatusEnums)auth_status);
            if(!String.IsNullOrEmpty(query.good_sku))
                filter = filter.And(c => c.GoodSKU == query.good_sku);
            var result = context.GoodDeclarations.FromCachePaged<GoodDeclaration, good_declaration_dto>(query.page, query.size, filter, orderBy => orderBy.OrderByDescending(c => c.Id), "GoodDeclaration");
            return result;
        }

		public ApiPagedResult<good_declaration_dto> GetGoodDeclarations(GoodDeclaQuery query) {
			var filter = PredicateBuilder.True<GoodDeclaration>();
                filter = filter.And(c => c.AuditStatus == (GoodDeclarationStatusEnums)query.auth_status);
			var merchant = context.Merchants.FirstOrDefault(c => c.MerchantNo == query.bind_no);
            
            //O商获取所有申报商品
            //if (merchant.IsOEM) {
            //    var sublevels = context.Merchants.Where(c => c.ParentId == merchant.Id).Select(c => c.Id).ToArray();
            //    var submerchant = context.MerchantDeclarations.Where(c => sublevels.Contains(c.MerchantId??0)).Select(c => c.Id).ToArray();
            //    filter = filter.And(c => submerchant.Contains(c.MerchantDecId));
            //} else {
            //    var merchantDecla = context.MerchantDeclarations.FirstOrDefault(c => c.MerchantId == merchant.Id);
            //    if (merchantDecla != null)
            //        filter = filter.And(c => c.MerchantDecId == merchantDecla.Id);
            //    else
            //        return ApiResultToJson.Json(new ApiPagedResult<good_declaration_dto>(null, 0, 1, 10));
            //}
        
            var list = context.GoodDeclarations.FromCachePaged<GoodDeclaration, good_declaration_dto>(query.page, query.size, filter, orderBy => orderBy.OrderByDescending(c => c.Id), "GoodDeclaration");
			var result = new ApiPagedResult<good_declaration_dto>(list.rows, list.total_result, list.page, list.size);
			return ApiResultToJson.Json(result);
		}

        public good_declaration_dto GetGoodDeclaration(GoodDeclarationQuery query) {
            var good = context.GoodDeclarations.FirstOrDefault(c => c.Id == query.id).ToDtoObject<good_declaration_dto>();
            return good;
        }

        public int AlterGoodDeclaration(good_declaration_dto dto) {
            var good = context.GoodDeclarations.FirstOrDefault(c => c.Id == dto.id);
            good.GoodSKU = dto.good_sku;
            good.CompanyName = dto.company_name;
            good.HSCode = dto.hs_code;
            good.GoodName = dto.good_name;
            good.GoodDescription = dto.good_description;
            good.Model = dto.model;
            good.Unit = dto.unit;
            good.MinUnit = dto.min_unit;
            good.Ingredient = dto.ingredient;
            good.Barcode = dto.barcode;
            good.Category = dto.category;
            good.Application = dto.application;
            good.ProducCountry = dto.produc_country;
            good.ProducCompany = dto.produc_company;
            good.Brand = dto.brand;
            good.Supplier = dto.supplier;
            good.AuditStatus = dto.audit_status;
            good.Tax = dto.tax;
            good.Weight = dto.weight;
            int result = _iUnitOfWork.Commit("GoodDeclaration");
            return result;
        }

        /// <summary>
        /// 商品申报备案
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public int SaveGoodDeclaration(good_declaration_dto dto) {
            var merchant_dec = context.MerchantDeclarations.Find(dto.merchant_id).ToDtoObject<merchant_declaration_dto>();
            if (merchant_dec.auth_status != MerchantDeclarationStatusEnums.Pass) {
                if (merchant_dec.auth_status == MerchantDeclarationStatusEnums.Wait)
                    throw new ServerErrorException("商家待审核中，请联系客服尽快审核！");
                else if (merchant_dec.auth_status == MerchantDeclarationStatusEnums.Fail)
                    throw new ServerErrorException("商家审核未通过，请重新提交审核！");
            }
            var good = dto.ToDtoObject<GoodDeclaration>();
            good.CreateTime = DateTime.Now.ToUnix();
            good.AuditStatus = GoodDeclarationStatusEnums.Wait;
            context.GoodDeclarations.Add(good);
            int result = _iUnitOfWork.Commit("GoodDeclaration");
            return result;
        }

        public int AuditGoodDeclaration(good_declaration_dto dto) {
            var good = context.GoodDeclarations.FirstOrDefault(c => c.Id == dto.id);
            good.AuditStatus = dto.audit_status;
            good.Tax = dto.tax;
            if(!string.IsNullOrEmpty(dto.file_code))
                good.FileCode = dto.file_code;
            int result = _iUnitOfWork.Commit("GoodDeclaration");
            return result;
        }

        public int DeleteGoodDeclaration(long id) {
            context.GoodDeclarations.Remove(id);
            int result = _iUnitOfWork.Commit("GoodDeclaration");
            return result;
        }

        public int Declaration(string[] ids, long user_id) {
            var goods = context.GoodDeclarations.ToList();
            foreach (var good in goods) {
                foreach (var id in ids) {
                    if (good.Id.ToString() == id)
                        good.AuditStatus = GoodDeclarationStatusEnums.Wait;
                }
            }
            var merchant = context.MerchantDeclarations.FirstOrDefault(c => c.Id == user_id);
            if(merchant.FeeCount > 0)
              merchant.FeeCount -= 1;
            int result = _iUnitOfWork.Commit("GoodDeclaration", "MerchantDeclaration");
            return result;
        }

        public bool VerifyGoodDeclaration(long id) {
            bool result = false;
            var goods = context.GoodDeclarations.FirstOrDefault(c => c.Id == id);
            if (goods != null && goods.AuditStatus == GoodDeclarationStatusEnums.Pass)
                result = true;
            return result;
        }

        /// <summary>
        /// 更新商品状态
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="status"></param>
        /// <param name="goodDecId"></param>
        /// <returns></returns>
        public int UpdateGoodDeclaration(long user_id, int status, long goodDecId) {
            var goodDec = context.GoodDeclarations.FindById(goodDecId);
            goodDec.AuditStatus = (GoodDeclarationStatusEnums)status;
            int result = _iUnitOfWork.Commit("GoodDeclaration");
            return result;
        }
    }
}
